const data = [
  { id: 1, pid: 0, name: '顶级节点' },

  { id: 2, pid: 1, name: '一级节点1' },

  { id: 3, pid: 1, name: '一级节点2' },

  { id: 4, pid: 2, name: '二级节点1' },

  { id: 5, pid: 2, name: '二级节点2' },

  { id: 6, pid: 2, name: '二级节点3' },

  { id: 7, pid: 3, name: '三级节点1' },

  { id: 8, pid: 3, name: '三级节点2' },

  { id: 9, pid: 3, name: '三级节点3' },
];

// 节点 -> 子节点
const nodesObj = {}

data.forEach(node => nodesObj[node.id] = node)

const node2ChildObj = {}

data.forEach(node => {
    if (!node2ChildObj[node.pid])
        node2ChildObj[node.pid] = [];
    node2ChildObj[node.pid].push(nodesObj[node.id]);
});

const nodeAndMemberObj = {};

const getChildren = (nodeId) => {
  const childNode = node2ChildObj[nodeId];
  if (childNode?.length == 0 || !childNode) {
    return {
      ...nodesObj[nodeId],
      sub: [],
    };
  }
    return nodesObj[nodeId][sub] = childNode.map(
        (node) => getChildren(node.id),
    );
};

const res = getChildren(0);
// 0 本身为 null -> sub: []
console.log(res)